package cn.pangza.user.service;

import cn.pangza.user.entity.po.Role;
import cn.pangza.user.entity.po.SystemUserPo;
import cn.pangza.user.mapper.RoleMapper;
import cn.pangza.user.mapper.SystemUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class SecurityUserService implements UserDetailsService {

    @Autowired
    SystemUserMapper systemUserMapper;

    @Autowired
    RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SystemUserPo> userPoQueryWrapper = new QueryWrapper<>();
        userPoQueryWrapper.eq("username", username);
        SystemUserPo systemUserPo = systemUserMapper.selectOne(userPoQueryWrapper);
        System.out.println("systemUserPo = " + systemUserPo);
        if(ObjectUtils.isEmpty(systemUserPo)) throw new UsernameNotFoundException("用户或密码输入错误");
        List<Role> roles = roleMapper.selectRoleListByUserId(systemUserPo.getId());
        systemUserPo.setRoleList(roles);
        return systemUserPo;
    }
}
